import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from '@/components/PageLoading';
import download from '@/utils/download';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Spin,
  Table,
  Tabs,
  Tag,
  Tooltip,
  Icon,
} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import Bottword from '@/modules/Bottword.js';
import React, { Component, Suspense } from 'react';
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from './index.less';
import qkls from '@/assets/versionMaintenance/qkls.png';
import riqi from '@/assets/versionMaintenance/riqi.png';
import Shape from '@/assets/versionMaintenance/Shape.png';
import dc from '@/assets/versionMaintenance/dc.png';

const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const Search = Input.Search;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const Option = Select.Option;

class AmendantRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      total: 0,
      dataSource: [],
      pageSize: 10,
      page: 1,
      login: false,
      query: '',
      a: false,
      img: '',
      rowId:''
    };
  }

  // eslint-disable-next-line react/sort-comp
  fetch = (qaId, from, to, page, limit, query) => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'amendantRecord/fetch',
        payload: { robotId: currentUser.robotId, qaId, from, to, page, limit, query },
        callback: res => {
          res.items.map((item, index) => (item['key'] = index));
          console.log('列表数据', res);
          this.setState({
            dataSource: res.items,
            total: res.total,
            login: false,
          });
        },
      });
    });
  };

  componentDidMount() {}

  componentWillMount() {
    let beginTime = moment(new Date())
      .subtract(7, 'days')
      .format('YYYY-MM-DD');
    let sysTime = moment(new Date()).format('YYYY-MM-DD');
    this.setState(
      {
        beginTime: beginTime,
        overTime: sysTime,
      },
      () => {
        this.fetch('', beginTime, sysTime, '', '', '');
      }
    );
    console.log(sysTime, beginTime);
  }

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState({
      beginTime: dateString[0].replace(/\//g, '-'),
      overTime: dateString[1].replace(/\//g, '-'),
    });

    console.log(date, dateString);
    const { beginTime, overTime, page, pageSize, query } = this.state;
    this.fetch(
      '',
      dateString[0].replace(/\//g, '-'),
      dateString[1].replace(/\//g, '-'),
      page,
      pageSize,
      query
    );
  };

  seekEnter = e => {
    console.log(e);
  };

  unfold = () => {
    console.log('展示');
  };

  openGaller = item => {
    this.setState({
      img: item,
      a: true,
    });
  };

  dateZdy = () => {
    return <img style={{ cursor: 'pointer' }} src={riqi} />;
  };

  dateZdya = () => {
    return <img style={{ cursor: 'pointer' }} src={Shape} />;
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    return (
      <div>
        <div className={styles.backgroundp}>
          <Card bodyStyle={{ background: '#f0f2f5' }} bordered={false}>
            <p className={styles.titleA}>版本维护</p>
            <div style={{ marginBottom: 20 }} className={styles.fromColumn}>
              <span className="zdyButtonQk">
                <img
                  onClick={this.clearHistory}
                  style={{ cursor: 'pointer', marginTop: 5 }}
                  src={qkls}
                />
              </span>
              <div style={{ float: 'right' }}>
                <Form className={styles.buttonA} layout="inline">
                  <FormItem className="zdyinput">
                    <RangePicker
                      suffixIcon={this.dateZdy()}
                      onChange={this.onChange}
                      style={{ height: 54, width: 312 }}
                      defaultValue={[
                        moment(this.state.beginTime, dateFormat),
                        moment(this.state.overTime, dateFormat),
                      ]}
                      format={dateFormat}
                    />
                  </FormItem>
                  <FormItem className="zdyinputa">
                    {getFieldDecorator('seek', {})(
                      <Search
                        // allowClear
                        // suffix = {this.dateZdya()}
                        placeholder="请输入搜索内容"
                        onSearch={value => {
                          console.log(value);
                          this.setState({ query: value, page: 1 }, () => {
                            const { beginTime, overTime, page, pageSize, query } = this.state;
                            this.fetch('', beginTime, overTime, page, pageSize, value);
                          });
                        }}
                        style={{ height: 54, width: 312 }}
                      />
                    )}
                  </FormItem>
                  <FormItem onClick={this.answerDetail} className="buttonYs">
                    <img onClick={this.answerDetail} style={{ marginTop: 5 }} src={dc} />
                    {/* <Button icon="arrow-down" onClick={this.answerDetail}>
                       
                        <FormattedMessage id="app.answerDetail.derive" defaultMessage="Download" />
                      </Button> */}
                  </FormItem>
                </Form>
              </div>
            </div>
            {this.lessdata()}
          </Card>
        </div>
        {/* <div style={{ textAlign: 'center' }}>
            <Bottword />
          </div> */}
      </div>
    );
  }

  clearHistory = () => {
    Modal['confirm']({
      title: '修改记录',
      content: '确认清除历史记录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        console.log('清空历史');
        const { dispatch, currentUser } = this.props;
        const { beginTime, overTime, page, pageSize, query } = this.state;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'amendantRecord/fetchc',
            payload: { robotId: currentUser.robotId },
            callback: res => {
              console.log('清空列表', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`);
                const { beginTime, overTime, page, pageSize, query } = this.state;
                this.fetch('', beginTime, overTime, page, pageSize, query);
              }
            },
          });
        });
      },
      onCancel() {
        console.log('onCancel');
      },
    });
  };

  setRowClassName = (expandedRows) => {
    console.log('111')
  }

  lessdata = () => {
    const { selectedRowKeys } = this.state;
    // 多选
    const columns = [
      {
        title: '问题',
        width: 'calc(25vw)',
        dataIndex: 'questions',
        render: aligns => (
          // <span>
          //   {aligns.map((item, index) => {
          //     if(index<5){
          //       return <p key={index}>{item}</p>;
          //     }
          //   })}
          //    {aligns.length>5?<div onClick={this.unfold} className={styles.zhankai}>展开 ∨</div>:null}
          // </span>

          <div className={styles.wtbj}>
            <div className={styles.wtbjB}>
              {aligns.map((item, index) => {
                return (
                  <p
                    dangerouslySetInnerHTML={{ __html: item }}
                    className={styles.phang}
                    key={index}
                  />
                );
              })}
            </div>
          </div>
        ),
      },
      {
        title: '回答',
        width: 'calc(25vw)',
        dataIndex: 'answers',
        render: item => {
          let b = item.map(val => {
            if (val.indexOf('img') != -1) {
              let a = val.replace('img', 'img style="maxWidth:90%"');
              return (
                <div onClick={() => this.openGaller(a)} dangerouslySetInnerHTML={{ __html: a }} />
              );
            } else {
              return <div dangerouslySetInnerHTML={{ __html: val }} />;
            }
          });
          return (
            <div className={styles.wtbjs}>
              <div className={styles.wtbjBs}>{b}</div>
            </div>
            // <div className={styles.hdbj}>{b}</div>
          );
        },
      },
      {
        title: '时间',
        dataIndex: 'time',
        width: 'calc(10vw)',
        render: dataIndex => {
          return moment(dataIndex).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: '85px',
        render: aligns => (
          <span>
            {// eslint-disable-next-line no-nested-ternary
            aligns === 'remove' ? (
              <Tag style={{ marginBottom: 2 }} color="#fa541c">
                移除
              </Tag>
            ) : aligns === 'create' ? (
              <Tag style={{ marginBottom: 2 }} color="#5092e1">
                创建
              </Tag>
            ) : (
              <Tag style={{ marginBottom: 2 }} color="#87d3ac">
                更新
              </Tag>
            )}
          </span>
        ),
      },
      {
        title: '操作人',
        width: 'calc(10vw)',
        dataIndex: 'operator',
      },
    ];
    return (
      <Spin spinning={this.state.login}>
        <Table
          // className="zdyTable"
          // style={{ background: '#fff',borderRadius:16 }}
          columns={columns}
          dataSource={this.state.dataSource} //数据
          pagination={{
            // 分页
            total: this.state.total,
            pageSize: this.state.pageSize, // 显示几条一页
            current: this.state.page, // 当前页
            showSizeChanger: true, // 是否显示可以设置几条一页的选项
            showQuickJumper: true,
            onChange: this.onChangeA,
            onShowSizeChange: this.onShowSizeChangeA,
          }}
        />
        <Modal
          style={{
            maxHeight: ' 90%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          }}
          width={'calc(80vw)'}
          height={'calc(80vh)'}
          className="modalovel"
          visible={this.state.a}
          title="图片详情"
          onCancel={() => {
            this.setState({
              a: false,
            });
          }}
          footer={null}
        >
          {<div dangerouslySetInnerHTML={{ __html: this.state.img }} />}
        </Modal>
      </Spin>
    );
  };

  onChangeA = val => {
    // 页数选择
    console.log(val);
    this.setState({ page: val });

    const { beginTime, overTime, page, pageSize, query } = this.state;
    this.fetch('', beginTime, overTime, val, pageSize, query);
  };

  // 每页显示多少条数据
  onShowSizeChangeA = (current, pageSize) => {
    console.log('1', current, '2', pageSize);
    this.setState({ pageSize: pageSize, page: current });
    const { beginTime, overTime, page, query } = this.state;
    this.fetch('', beginTime, overTime, current, pageSize, query);
  };

  answerDetail = () => {
    // fetchb
    const { dispatch } = this.props;
    const data = {
      query: this.state.query,
      fileType: 'xlsx',
      from: this.state.beginTime,
      to: this.state.overTime,
      qaId: '',
    };
    dispatch({
      type: 'amendantRecord/fetchb',
      payload: data,
      callback: res => {
        let filename = decodeURIComponent(
          res.requestRes.headers.get('Content-Disposition').split('=')[1]
        );
        download.byBlob(res.fileBlob, filename);
      },
    });
  };
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AmendantRecord));
